import { login, logout, getUserInfo } from '@/apis/login'
import { setStorage, removeStorage, getStorage } from '@/utils/lib'

const state = {
    // 是否登录
    isLogin: false,

    // 当前登录用户
    userName: "",
}

const mutations = {
    // 设置登录状态
    setLoginState(state, status) {
        state.isLogin = status
    },

    // 设置当前用户
    setUsername(state, name) {
        state.userName = name
    },

    // 存储 token
    setToken(state, token) {
        setStorage('token', token)
    },

    // 删除 token
    removeToken() {
        removeStorage('token')
    },

    // 存储用户信息
    saveUserInfo(state, userInfo) {
        setStorage('userInfo', userInfo)
    },

    // 删除用户信息
    removeUserInfo() {
        removeStorage('userInfo')
    },
}

const actions = {
    // 登录
    async login(ctx, params) {
        let data = await login(params)

        if (data) {
            ctx.commit('setToken', data.token)
            ctx.commit('setLoginState', true)

            let userInfo = await getUserInfo()

            if (userInfo) {
                ctx.commit('setUsername', userInfo.user.userName)
                ctx.commit('saveUserInfo', userInfo)
            }

            return new Promise((resolve) => {
                resolve(data)
            })
        }
    },

    // 退出登录
    async logout(ctx) {
        let token = getStorage('token')
        let data = await logout(token)

        if (data) {
            ctx.commit('removeToken')
            ctx.commit('setLoginState', false)

            return new Promise((resolve) => {
                resolve(data)
            })
        }
    },

    // 获取用户信息
    getUserInfo() {},
}

const getters = {}

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}
